package com.bruce.tool.netty.socket.core;

import com.bruce.tool.netty.socket.config.BaseConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;

/**
 * 功能 :
 *
 * @author : Bruce(刘正航) 10:36 2019-03-10
 */
@Component
public class SocketServer implements Start{

    private final SocketServerHandler handler = new SocketServerHandler(this);
    @Getter
    private BaseConfig config = new BaseConfig();
    @Setter
    private Integer port = 8888;

    @Override
    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(handler);
                        }
                    });
            ChannelFuture f = b.bind(port).sync();
            Channel channel = f.channel();
            channel.closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
